package net.piggy.core.inercept;

import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.*;
import net.piggy.core.executor.common.SessionResult;
import net.piggy.core.model.HttpStatement;
import net.piggy.core.session.GatewaySession;

public class MethodIntercept extends HystrixCommand<Object>{
    private final GatewaySession session;
    private final HttpStatement httpStatement;
    private final JSONObject json;
    public MethodIntercept(GatewaySession session, HttpStatement httpStatement, JSONObject json) {
        super(HystrixCommand.Setter
                .withGroupKey(HystrixCommandGroupKey.Factory.asKey(httpStatement.getApplicationName()))
                .andCommandKey(HystrixCommandKey.Factory.asKey("key"+httpStatement.getUri().replace("/",":")))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(httpStatement.getApplicationName()))
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(100))
                .andCommandPropertiesDefaults(
                        HystrixCommandProperties.Setter()
                                .withCircuitBreakerEnabled(true)
                                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
                                .withExecutionTimeoutInMilliseconds(10000)
                                .withCircuitBreakerRequestVolumeThreshold(10)
                                .withCircuitBreakerErrorThresholdPercentage(80)
                )
        );
        this.json = json;
        this.session = session;
        this.httpStatement = httpStatement;
    }

    @Override
    protected Object getFallback() {
        return SessionResult.buildError("server fallback");
    }

    @Override
    protected Object run() {
        return session.get(httpStatement, json);
    }
}
